package com.jiuyou.clientController.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.huifu.adapay.core.AdapayCore;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.core.util.AdapaySign;
import com.huifu.adapay.model.Payment;
import com.huifu.adapay.model.PaymentReverse;
import com.huifu.adapay.model.Refund;
import com.jiuyou.clientController.base.ClientBaseController;
import com.ruoyi.adapayRecord.domain.AdapayRecord;
import com.ruoyi.adapayRecord.service.IAdapayRecordService;
import com.ruoyi.adapayRefund.domain.AdapayRefund;
import com.ruoyi.adapayRefund.service.IAdapayRefundService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.domain.model.LoginMember;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OrderNoUtil;
import com.ruoyi.common.utils.QRCodeUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.img.ImgUtil;
import com.ruoyi.coupons.domain.CouponsMember;
import com.ruoyi.coupons.service.ICouponsMemberService;
import com.ruoyi.coupons.service.ICouponsService;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.member.service.IMemberService;
import com.ruoyi.order.domain.StoreProductOrder;
import com.ruoyi.order.domain.StoreProductOrderHandle;
import com.ruoyi.order.service.IStoreProductOrderHandleService;
import com.ruoyi.order.service.IStoreProductOrderService;
import com.ruoyi.product.domain.StoreProduct;
import com.ruoyi.product.domain.StoreProductBack;
import com.ruoyi.product.domain.StoreProductJoint;
import com.ruoyi.product.service.IStoreProductBackService;
import com.ruoyi.product.service.IStoreProductJointService;
import com.ruoyi.product.service.IStoreProductService;
import com.ruoyi.shopping.domain.MallIntegral;
import com.ruoyi.shopping.service.IMallIntegralRecordService;
import com.ruoyi.shopping.service.IMallIntegralService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.OrderUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 订单
 *
 * @author jiuyou
 */
@RestController
@RequestMapping("/client/order")
@Api(tags = {"C端订单下单"})
public class OrderClientController extends ClientBaseController {
    private static final Logger log = LoggerFactory.getLogger(OrderClientController.class);

    @Autowired
    private IStoreProductOrderService orderService;
    @Autowired
    private IStoreProductOrderHandleService handleService;
    @Autowired
    private ICouponsService couponsService;
    @Autowired
    private ICouponsMemberService couponsMemberService;
    @Autowired
    private IStoreProductBackService productBackService;
    @Autowired
    private IStoreProductService productService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IStoreProductOrderService storeProductOrderService;
    @Autowired
    private IAdapayRecordService adapayRecordService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IAdapayRefundService adapayRefundService;
    @Autowired
    private IMallIntegralRecordService recordService;
    @Autowired
    private IMallIntegralService integralService;
    @Autowired
    private IStoreProductJointService storeProductJointService;
    @Autowired
    /**
     * 充值会员卡
     * */
    @PostMapping("/createVip")
    public AjaxResult create(){
        Long  loginMemberId= getLoginMemberId();
        if(null==loginMemberId){
            return AjaxResult.error("刷新后再试");
        }
        String vip_price = configService.selectConfigByKey("vip_price");//vip价格

        //生成订单号
        StoreProductOrder order = new StoreProductOrder();
        Long memberId = getLoginMemberId();
        order.setOrderId(OrderNoUtil.getOrderNo(memberId));
        order.setOrderState(DicConstants.ORDER_STATE_Wait_Pay.getCode());
        order.setMemberId(memberId);
//            order.setStoreId(product.getStoreId());
        //order.setStoreId(storeId);
//        order.setStoreName(product.getStoreName());
//        order.setProductImage(product.getProductImage());
        order.setTotalPrice(new BigDecimal(vip_price));
        order.setPayPrice(new BigDecimal(vip_price));
        order.setOrderType("vip");
        order.setProductName("vip升级");

        orderService.insertStoreProductOrder(order);
        /*//改变会员时间
        Long member_id = order.getMemberId();
        Member memberOne = memberService.selectMemberById(member_id);
        if( memberOne.getVipEndDate() == null){
            //直接加入时间 ，订单下单时候加上一年
            // 当前日期时间
            Date now =   DateUtils.getNowDate();
            System.out.println("当前日期时间: " + now);
            // 添加365天
            Date newDate = DateUtils.addDays(now, 365);
            System.out.println("New Date after adding 365 days: " + newDate);

            Member member = new Member();
            member.setId(member_id);
            member.setVipEndDate(newDate);
            member.setIsVip("Y");
            memberService.updateMember(member);
        }else{
            //原有时间加上一年
            Date now =   memberOne.getVipEndDate();
            System.out.println("当前日期时间: " + now);
            // 添加365天
            Date newDate = DateUtils.addDays(now, 365);
            System.out.println("New Date after adding 365 days: " + newDate);

            Member member = new Member();
            member.setId(member_id);
            member.setVipEndDate(newDate);
            member.setIsVip("Y");
            memberService.updateMember(member);

        }
*/

        return AjaxResult.success(order);
    }

    @PostMapping("/create")
    @ApiOperation("创建订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "couponId", value = "优惠券ID", required = false, dataType = "Long"),
    })
    public AjaxResult create(Long productId, Long couponId,Long storeId ,String integral) throws Exception {
          Long  loginMemberId= getLoginMemberId();
          if(null==loginMemberId){
              return AjaxResult.error("刷新后再试");
          }
          if(storeId == null){
              return AjaxResult.error("storeId 不能为空");
          }
            //查询商品
            StoreProductOrder order = new StoreProductOrder();
            order.setProductId(productId);

            StoreProduct product = productService.selectStoreProductById(order.getProductId());
//            if (null == product||!DicConstants.SYS_Y.getCode().equals(product.getState())) {
//                return AjaxResult.error("商品已经下架了");
//            }

           if( DicConstants.SYS_Y.getCode().equals( product.getNewUserState())){
               if(!isNewUser(product.getStoreId())){
                   return AjaxResult.error("该商品仅限新人购买");
               }
           }
           if(product.getWriteOffNum() == null){
               order.setWriteOffNum(1L);//核销次数
           }else{
               order.setWriteOffNum(product.getWriteOffNum());//核销次数
           }
            order.setProductBackId(product.getProductBackId());
            order.setProductName(product.getProductName());
            Long memberId = getLoginMemberId();
            //生成订单号
            order.setOrderId(OrderNoUtil.getOrderNo(memberId));
            order.setOrderState(DicConstants.ORDER_STATE_Wait_Pay.getCode());
            order.setMemberId(memberId);
//            order.setStoreId(product.getStoreId());
            order.setStoreId(storeId);
            order.setStoreName(product.getStoreName());
            order.setProductImage(product.getProductImage());
            order.setTotalPrice(product.getPrice());
            order.setPayPrice(product.getPrice());
            if(DicConstants.SYS_Y.getCode().equals(product.getFixedTimeState())){
                Date date = DateUtils.addDate(Integer.parseInt(product.getValidDay().toString()));
                order.setLastUseTime(date);
            }else {
                order.setLastUseTime(product.getUseEndTime());
            }
            //优惠前应付金额
            BigDecimal yfprice=product.getPrice();
            //把优惠券变为已经使用
            if (null != couponId) {
                //此处应该检查所选优惠券是否可用,也可以在查看团单详情的时候直接返回可用优惠券
                CouponsMember couponsMemberQu=new CouponsMember();
                couponsMemberQu.setCouponId(couponId);
                couponsMemberQu.setMemberId(loginMemberId);
                CouponsMember memberCoupon=null;
                List<CouponsMember> listeCm= couponsMemberService.selectCouponsMemberList(couponsMemberQu);
                if(listeCm.size()>0){
                    memberCoupon=listeCm.get(0);
                }else{
                    return AjaxResult.error("未找到可用优惠券");
                }
                if(memberCoupon.getMinPrice().compareTo(product.getPrice())==1){
                    //不足最低金额
                    return AjaxResult.error("该优惠券不可用");
                }
                if(DicConstants.SYS_Y.getCode().equals(memberCoupon.getUseState())){
                    return AjaxResult.error("该优惠券不可用");
                }
                //判断用户是否是当前门店的新人用户
                if( DicConstants.SYS_Y.getCode().equals( memberCoupon.getNewUserState())) {
                    if(!isNewUser(memberCoupon.getStoreId())){
                        return AjaxResult.error("该优惠券仅限新人使用");
                    }
                }
                if(DicConstants.COUPON_TYPE_Product.getCode().equals(memberCoupon.getBelongType())){
                    String[] strings = StringUtils.deleteArrayNull(memberCoupon.getPrimaryKey().split(","));
                    if(Arrays.asList(strings).contains(product.getId().toString())){
                        return AjaxResult.error("商品不可使用该优惠券");
                    }

                }
                if(DicConstants.COUPON_TYPE_Classify.getCode().equals(memberCoupon.getBelongType())){
                    String[] strings = StringUtils.deleteArrayNull(memberCoupon.getPrimaryKey().split(","));
                    if(Arrays.asList(strings).contains(product.getClassifyId().toString())){
                        return AjaxResult.error("该分类不可使用当前优惠券");
                    }
                }
                order.setCouponId(memberCoupon.getId());
                memberCoupon.setUseTime(new Date());
                memberCoupon.setUseState(DicConstants.SYS_Y.getCode());
                memberCoupon.setUpdateBy(memberId);
                memberCoupon.setUpdateType(DicConstants.BUSINESS_Customer.getCode());
                couponsMemberService.updateCouponsMember(memberCoupon);
                order.setCouponPrice(memberCoupon.getMoney());
                order.setPayPrice(product.getPrice().subtract(memberCoupon.getMoney().setScale(2, RoundingMode.HALF_UP)));

                if(order.getPayPrice().compareTo(BigDecimal.ZERO)<1){
                    order.setPayPrice(new BigDecimal("0.01"));
                }
            }
            order.setDeductionPrice( yfprice.subtract(order.getPayPrice()).setScale(2,RoundingMode.HALF_UP));

//            if(DicConstants.SYS_Y.getCode().equals(integral))
//                handleIntegral(order);
            //读取抽佣比例并计算
            String ratio = configService.selectConfigByKey("commission_percent");
            order.setCommissionPercent(new BigDecimal(ratio).setScale(2,RoundingMode.HALF_UP));
            BigDecimal commissionPercent=order.getCommissionPercent();
            BigDecimal payPrice= order.getPayPrice();
            BigDecimal storepercent=new BigDecimal("1").subtract(commissionPercent.divide(new BigDecimal("100"),2,RoundingMode.HALF_UP));
            BigDecimal storeMoney=storepercent.multiply(payPrice).setScale(2,RoundingMode.HALF_UP);
            order.setStoreMoney(storeMoney);
            order.setPlatformMoney(payPrice.subtract(storeMoney).setScale(2,RoundingMode.HALF_UP));
            order.setPayState(DicConstants.SYS_N.getCode());

            //存入售后信息
            StoreProductJoint storeProductJoint = storeProductJointService.selectStoreProductByStoreIdAndStoreId(storeId,productId);
        order.setIsAfterSales(storeProductJoint.getIsAfterSales());
        order.setAftersaleOffNum(storeProductJoint.getAsNum());
        order.setAftersaleStartTime(storeProductJoint.getAsStartTime());
        order.setAftersaleEndTime(storeProductJoint.getAsEndTime());
        order.setAftersaleMoney(storeProductJoint.getAsMoney());

        //生成售后码，售后二维码
        genAftersaleCode(order);

            orderService.insertStoreProductOrder(order);
            //销量+1
            product.setSalesNum(product.getSalesNum()+1L);
            productService.updateStoreProduct(product);
            //生成订单操作记录
            StoreProductOrderHandle orderHandle = new StoreProductOrderHandle();
            orderHandle.setCreateType(DicConstants.BUSINESS_Customer.getCode());
            orderHandle.setCreateBy(memberId);
            orderHandle.setHandleUserId(memberId);
            orderHandle.setHandleUserName(getUsername());
            orderHandle.setHandleName("创建订单");
            orderHandle.setOrderId(order.getId());
            orderHandle.setHandleDetail(order.toString());
            orderHandle.setHandleOrderType(DicConstants.ORDER_PRODUCT.getCode());
            handleService.insertStoreProductOrderHandle(orderHandle);
            /*try{
                doSuccess(order.getId());
            }catch (Exception e){

            }*/
            //将平台券和商家新人券置为不可用
            List<CouponsMember> coupons = couponsMemberService.selectCoupons(memberId,DicConstants.SYS_N.getCode(),DicConstants.SYS_Y.getCode());
            ArrayList<Long> couponsIds = new ArrayList<>();
            coupons.forEach(e->{
                couponsIds.add(e.getId());
            });
            if(couponsIds.size()>0)
                couponsMemberService.setOldUser(couponsIds);
            return AjaxResult.success(order);
    }

    private void handleIntegral(StoreProductOrder order) {
        BigDecimal payPrice = order.getPayPrice();
        BigDecimal proportion = new BigDecimal(configService.selectConfigByKey("proportion"));
        if(proportion.compareTo(BigDecimal.ZERO)<1){
            return;
        }
        MallIntegral mineIntegral = integralService.selectByUserId(getLoginMemberId());
        if(mineIntegral == null || mineIntegral.getIntegralBalance().compareTo(BigDecimal.ZERO)<1){
            return;
        }
    }

    private void genVerifyCode(StoreProductOrder order) throws Exception{
        String verifyCode = OrderNoUtil.getNum(8);
        StoreProductOrder order1 = orderService.selectVerify(verifyCode, order.getStoreId());
        if(order1 != null){
            genVerifyCode(order);
        }else{
            order.setVerifyCode(verifyCode);
            String content = verifyCode;
            String s = DateUtils.datePath();
            String path =  RuoYiConfig.getUploadPath()+"/verifyCode/"+s;// 二维码保存的路径
            String codeName = UUID.randomUUID().toString();// 二维码的图片名
            String imageType = "jpg";// 图片类型
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, "1");
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
            File file1 = new File(path, codeName + "." + imageType);
            QRCodeUtils.writeToFile(bitMatrix,imageType,file1);
            path = serverConfig.getUrl() + Constants.RESOURCE_PREFIX + "/upload/verifyCode/" +s+"/"+ codeName+"."+imageType;

            order.setVerifyCodeImg(path);

        }
    }
    public static void main(String[] args) throws WriterException, IOException {
//        String content = "12213366fsafsadfsafadfafsa";
//        String s = DateUtils.datePath();
//        String path =  "D:/verify";// 二维码保存的路径
//        String codeName = UUID.randomUUID().toString();// 二维码的图片名
//        String imageType = "jpg";// 图片类型
//        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
//        Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
//        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 100, 100, hints);
//        File file1 = new File(path, codeName + "." + imageType);
//        QRCodeUtils.writeToFile(bitMatrix,imageType,file1);
//        BigDecimal bigDecimal = new BigDecimal("0.1");
//        BigDecimal bigDecimal1 = new BigDecimal("0.2");
//        System.out.println(bigDecimal.compareTo(BigDecimal.ZERO));
    }

    private void genAftersaleCode(StoreProductOrder order) throws Exception{
        String aftersaleCode = OrderNoUtil.getNum(8);
        StoreProductOrder order1 = orderService.selectAftersale(aftersaleCode, order.getStoreId());
        if(order1 != null){
            genAftersaleCode(order);
        }else{
            //order.setVerifyCode(verifyCode);
            order.setAftersaleCode(aftersaleCode);
            String content = aftersaleCode;
            String s = DateUtils.datePath();
            String path =  RuoYiConfig.getUploadPath()+"/aftersaleCode/"+s;// 二维码保存的路径
            String codeName = UUID.randomUUID().toString();// 二维码的图片名
            String imageType = "jpg";// 图片类型
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, "1");
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
            File file1 = new File(path, codeName + "." + imageType);
            QRCodeUtils.writeToFile(bitMatrix,imageType,file1);
            path = serverConfig.getUrl() + Constants.RESOURCE_PREFIX + "/upload/aftersaleCode/" +s+"/"+ codeName+"."+imageType;

            //order.setVerifyCodeImg(path);
            order.setAftersaleCodeImg(path);

        }
    }

    //vip成功操作
    private void doVipSuccess(Long orderId,String orderNo) throws Exception {
        StoreProductOrder order = orderService.selectStoreProductOrderById(orderId);
        order.setPayTime(new Date());
        order.setPayOrderNo(orderNo);

        //支付成功后将状态置为 已经完成
        order.setOrderState(DicConstants.ORDER_STATE_FINISHED.getCode());
        order.setPayState(DicConstants.SYS_Y.getCode());
        orderService.updateStoreProductOrder(order);

        //改变会员时间
        Long member_id = order.getMemberId();
        Member memberOne = memberService.selectMemberById(member_id);
        if( memberOne.getVipEndDate() == null){
            //直接加入时间 ，订单下单时候加上一年
            // 当前日期时间
            Date now =   DateUtils.getNowDate();
            System.out.println("当前日期时间: " + now);
            // 添加365天
            Date newDate = DateUtils.addDays(now, 365);
            System.out.println("New Date after adding 365 days: " + newDate);

            Member member = new Member();
            member.setId(member_id);
            member.setVipEndDate(newDate);
            member.setIsVip("Y");
            memberService.updateMember(member);
        }else{
            //原有时间加上一年
            Date now =   memberOne.getVipEndDate();
            System.out.println("当前日期时间: " + now);
            // 添加365天
            Date newDate = DateUtils.addDays(now, 365);
            System.out.println("New Date after adding 365 days: " + newDate);

            Member member = new Member();
            member.setId(member_id);
            member.setVipEndDate(newDate);
            member.setIsVip("Y");
            memberService.updateMember(member);

        }

    }

    private void doSuccess(Long orderId,String orderNo) throws Exception {
        StoreProductOrder order = orderService.selectStoreProductOrderById(orderId);
//        Long memberId = getLoginMemberId();
        order.setPayTime(new Date());
        order.setPayOrderNo(orderNo);

        //支付成功后将状态置为待使用
        order.setOrderState(DicConstants.ORDER_STATE_Wait_Use.getCode());
        order.setPayState(DicConstants.SYS_Y.getCode());
        //order.setPayPrice(new BigDecimal("0"));
        genVerifyCode(order);

        //生成售后码，售后二维码
        genAftersaleCode(order);

//        order.setPayOrderNo("记录单号");
        //结算状态
//            order.setBilingState()
        //支付成功后才可结算
        //查看商品是有效期还是固定有效
       /* StoreProductBack back = productBackService.selectStoreProductBackById(order.getProductBackId());
        if(DicConstants.SYS_Y.getCode().equals(back.getFixedTimeState())){
            Date date = DateUtils.addDate(Integer.parseInt(back.getValidDay().toString()));
            order.setLastUseTime(date);
        }else {
            order.setLastUseTime(back.getUseEndTime());
        }*/
        order.setBillingState(DicConstants.BILLING_STATE_No.getCode());

        orderService.updateStoreProductOrder(order);
        StoreProductOrderHandle orderHandle = new StoreProductOrderHandle();
        orderHandle.setCreateType(DicConstants.BUSINESS_Customer.getCode());
        orderHandle.setCreateBy(0L);
        orderHandle.setOrderId(orderId);
        orderHandle.setHandleName("支付回调");
        orderHandle.setHandleDetail(order.toString());
        handleService.insertStoreProductOrderHandle(orderHandle);
    }

   /* @PostMapping("/payOrder/{orderId}")
    @ApiOperation("支付订单")
    public JSONObject payOrder(@PathVariable Long orderId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", false);
        jsonObject.put("msg", "创建失败");
        try {
            StoreProductOrder order = orderService.selectStoreProductOrderById(orderId);
            Long memberId = getLoginMemberId();
            order.setPayTime(new Date());
            order.setPayOrderNo(OrderNoUtil.getOrderNo(memberId));
            //发起支付
            // ------------------------------------
            // ------------------------------------
            orderService.updateStoreProductOrder(order);
            jsonObject.put("success", true);
            jsonObject.put("msg", "创建成功");
            return jsonObject;
        } catch (Exception e) {
            return jsonObject;
        }
    }*/

  /*  @PostMapping("/callback")
    @ApiOperation("支付回调处理")
    public JSONObject callback(Long orderId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", false);
        jsonObject.put("msg", "创建失败");
        try {
            StoreProductOrder order = orderService.selectStoreProductOrderById(orderId);
            Long memberId = getLoginMemberId();
//            order.setPayOrderNo(OrderNoUtil.getOrderNo(memberId));

            //支付成功后将状态置为待使用
            order.setOrderState(DicConstants.ORDER_STATE_Wait_Use.getCode());
            order.setPayPrice(new BigDecimal("0"));
            order.setPayOrderNo("记录单号");
            //结算状态
//            order.setBilingState()
            //支付成功后才可结算
            order.setBillingState(DicConstants.BILLING_STATE_No.getCode());
            orderService.updateStoreProductOrder(order);
            StoreProductOrderHandle orderHandle = new StoreProductOrderHandle();
            orderHandle.setCreateType(DicConstants.BUSINESS_Customer.getCode());
            orderHandle.setCreateBy(0L);
            orderHandle.setHandleName("支付回调");
            orderHandle.setHandleDetail(order.toString());
            handleService.insertStoreProductOrderHandle(orderHandle);
            jsonObject.put("success", true);
            jsonObject.put("msg", "创建成功");
            return jsonObject;
        } catch (Exception e) {
            return jsonObject;
        }
    }*/

    /**
     * 需要支付的订单id
     * @param orderId
     * @return
     */
    @PostMapping("/delayPay")
    public AjaxResult delayPay( Long orderId)  {
        StoreProductOrder storeProductOrder=storeProductOrderService.selectStoreProductOrderById(orderId);

        if (null == storeProductOrder) {
            return AjaxResult.error("未找到该订单");
        }
        Long loginMemberId= getLoginMemberId();
        if(null==loginMemberId){
            return AjaxResult.error("刷新后再试");
        }
        Member member= memberService.selectMemberById(loginMemberId);
        if(member.getId().compareTo(storeProductOrder.getMemberId())!=0){
            return AjaxResult.error("警告：请勿支付他人订单");
        }
        if(!DicConstants.SYS_N.getCode().equals( storeProductOrder.getPayState())){
            return AjaxResult.error("该订单无需支付");
        }
        //调用sdk方法，创建支付，得到支付对象
        Map<String, Object> payment = new HashMap<>();
        System.out.println("=======execute payment begin=======");
        //创建支付对象的参数，全部参数请参考 https://docs.adapay.tech/api/index.html
        Map<String, Object> paymentParams = new HashMap<>(10);
        String app_id=configService.selectConfigByKey("adpay_app_id");
        paymentParams.put("app_id", app_id);
        String order_no="wx" + System.currentTimeMillis();
        paymentParams.put("order_no", order_no);
        paymentParams.put("pay_channel", "wx_lite");
        BigDecimal payPrice=storeProductOrder.getPayPrice();
        if(payPrice.compareTo(new BigDecimal("0"))==0){
            return AjaxResult.error("0元订单无法支付");
        }
        String pay_amt=storeProductOrder.getPayPrice().toString();
        paymentParams.put("pay_amt", pay_amt);

        paymentParams.put("goods_title", storeProductOrder.getProductName());
        paymentParams.put("goods_desc", storeProductOrder.getProductName());

        paymentParams.put("div_members", "");
        paymentParams.put("pay_mode", "delay");
        Map<String, Object> expendParams = new HashMap<>(2);
        String openId = member.getOpenId();//微信授权获取
        expendParams.put("open_id", openId);
        paymentParams.put("expend", expendParams);
        String domain=configService.selectConfigByKey("domain");
        String notify_url=/*request.getScheme()+*/domain+"/prod-api/client/order/notify";
        paymentParams.put("notify_url", notify_url);

        AdapayRecord adapayRecord=new AdapayRecord();
        adapayRecord.setPayOrderId(order_no);
        adapayRecord.setReqState(DicConstants.SYS_Y.getCode());
        adapayRecord.setProductOrderId(orderId);
        adapayRecord.setReqParam(paymentParams.toString());
        adapayRecord.setCreateBy(member.getId());
        adapayRecord.setBelongType("product");
        try {

            payment = Payment.create(paymentParams);
        } catch (BaseAdaPayException e) {
            e.printStackTrace();
            adapayRecord.setReqState((DicConstants.SYS_N.getCode()));
            adapayRecord.setReqFailMsg(e.getMessage());
            adapayRecordService.insertAdapayRecord(adapayRecord);
           return AjaxResult.error(e.getMessage());
        }
        adapayRecord.setResParam(payment.toString());
        String error_code = (String) payment.get("error_code");
        if (null != error_code) {

            String error_msg = (String) payment.get("error_msg");
            System.out.println("error_code:" + error_code + "............." + error_msg);
            adapayRecord.setReqState((DicConstants.SYS_N.getCode()));
            adapayRecord.setReqFailMsg(error_msg);
            adapayRecordService.insertAdapayRecord(adapayRecord);
            return AjaxResult.error(error_msg);
        }

        adapayRecord.setPaymentId( (String)payment.get("id"));
        adapayRecordService.insertAdapayRecord(adapayRecord);
        return  AjaxResult.success(payment);
    }

    /**
     * 支付付款回调
     * @param request
     */
    @RequestMapping("/notify")
    public void notify(HttpServletRequest request) {
        try {
            //验签请参data
            String data = request.getParameter("data");
            //验签请参sign
            String sign = request.getParameter("sign");
            //验签标记
            boolean checkSign;
            //验签请参publicKey
            String publicKey = AdapayCore.PUBLIC_KEY;
            log.info("验签请参：data={}sign={}");
            //验签
            checkSign = AdapaySign.verifySign(data, sign, publicKey);
            if(checkSign){
                //验签成功逻辑
                System.out.println("成功返回数据data:"+data);
              JSONObject dataJson= JSONObject.parseObject(data);
                // pending 交易处理中 succeeded 交易成功 failed失败

                String order_no=dataJson.getString("order_no");//交易订单号？wx开头加时间戳
                AdapayRecord adapayRecordQuery=new AdapayRecord();
                adapayRecordQuery.setPayOrderId(order_no);
                List<AdapayRecord>  list=adapayRecordService.selectAdapayRecordList(adapayRecordQuery);
                if(list.size()>0){
                    AdapayRecord adapayRecord=list.get(0);

                    String payState=adapayRecord.getPayState();
                    if("succeeded".equals(payState)){
                        //已经处理过
                        return;
                    }
                    AdapayRecord adapayRecordUpdate=new AdapayRecord();
                    adapayRecordUpdate.setId(adapayRecord.getId());
                    adapayRecordUpdate.setNotifyParam(data);
                    String status=dataJson.getString("status");
                    String error_msg=dataJson.getString("error_msg");
                    adapayRecordUpdate.setPayState(status);
                    if("succeeded".equals(status)){
                        //交易成功
                        //判断是团购订单 还是vip升级订单
                        StoreProductOrder order = orderService.selectStoreProductOrderById(adapayRecord.getProductOrderId());
                        if(order.getOrderType().equals("vip")){
                            doVipSuccess(adapayRecord.getProductOrderId(),order_no);

                        }else{
                            doSuccess(  adapayRecord.getProductOrderId(),order_no);
                        }

                    }
                    if("failed".equals(status)){
                        //交易失败
                        adapayRecordUpdate.setPayFailMsg(error_msg);
                    }
                    adapayRecordUpdate.setUpdateTime(new Date());
                    adapayRecordService.updateAdapayRecord(adapayRecordUpdate);
                }

            }else {
                //验签失败逻辑
            }
        }catch (Exception e){
            log.info("异步回调开始，参数，request={}");
        }
        return ;
    }

    @PostMapping("refundApply")
    public AjaxResult refundApply(Long orderId,String cause){
        Long loginMemberId = getLoginMemberId();
        StoreProductOrder order = orderService.selectStoreProductOrderById(orderId);
        if(null == order){
            return AjaxResult.error("订单不存在");
        }
//        order.setRefundPayStatus(DicConstants.REFUND_STATUS_Apply.getCode());
//        order.setOrderState(DicConstants.ORDER_STATE_Refund_Apply.getCode());
        order.setRefundPrice(order.getPayPrice());
        order.setRefundReason(cause);
        order.setRefundTime(new Date());
        //暂时不需要审核
        order.setRefundStatus(DicConstants.REFUND_STATUS_Pass.getCode());
        order.setAftersaleState(DicConstants.SYS_Y.getCode());
        orderService.updateStoreProductOrder(order);
        return AjaxResult.success("退款请求已发起");
    }

    /**
     * 退款支付回调
     * @param request
     */
    @RequestMapping("/refundPayNotify")
    public void refundPayNotify(HttpServletRequest request) {
        try {
            //验签请参data
            String data = request.getParameter("data");
            //验签请参sign
            String sign = request.getParameter("sign");
            //验签标记
            boolean checkSign;
            //验签请参publicKey
            String publicKey = AdapayCore.PUBLIC_KEY;
            log.info("验签请参：data={}sign={}");
            //验签
            checkSign = AdapaySign.verifySign(data, sign, publicKey);
            if(checkSign){
                //验签成功逻辑
                System.out.println("refundPayNotify成功返回数据退款回调data:"+data);
                JSONObject dataJson= JSONObject.parseObject(data);
                String order_no=dataJson.getString("order_no");//交易订单号？
                AdapayRefund adapayRefundQuery=new AdapayRefund();
                adapayRefundQuery.setRefundOrderNo(order_no);
                List<AdapayRefund> listre=   adapayRefundService.selectAdapayRefundList(adapayRefundQuery);
                if(listre.size()>0){
                    AdapayRefund adapayRefund=listre.get(0);
                    String refundState=  adapayRefund.getRefundState();
                    if("succeeded".equals(refundState)){
                        //已经处理过
                        return;
                    }

                    AdapayRefund adapayRefundUpdate=new AdapayRefund();
                    adapayRefundUpdate.setId(adapayRefund.getId());
                    String status=dataJson.getString("status");
                    adapayRefundUpdate.setRefundState(status);
                    Long productOrderId=  adapayRefund.getProductOrderId();
                    StoreProductOrder storeProductOrder=new StoreProductOrder();
                    storeProductOrder.setId(productOrderId);
                    if("succeeded".equals(status)){
                        //退款成功
                        storeProductOrder.setRefundPayStatus(DicConstants.SYS_Y.getCode());
                    }
                    if("failed".equals(status)){
                        //交易失败
                        storeProductOrder.setRefundPayStatus(DicConstants.SYS_N.getCode());
                    }
                    storeProductOrderService.updateStoreProductOrder(storeProductOrder);
                    adapayRefundUpdate.setUpdateTime(new Date());
                    adapayRefundUpdate.setNotifyParam(data);
                    adapayRefundService.updateAdapayRefund(adapayRefundUpdate);
                }

            }else {
                //验签失败逻辑
            }
        }catch (Exception e){
            log.info("异步回调开始，参数，request={}");
        }
        return ;
    }
}
